﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Components.Enum;
using Controls;
using Components;
using Model.Enum;
using UI.Common;
using UI.Lib.Factory;
using UI.Lib;
using Com.Seezt.Skins;
using System.Collections;
using ReturnPageData = Model.ReturnPageData;

namespace UI.ParentForm
{
    public partial class BaseMain : BaseForm
    {
        private BindingManagerBase BindingManager;
        private bool IsUntallKey = false; //是否卸载全局键
        protected bool IsChildLoadComplete = false; //子页面是否已经加载好了
        private int gridViewHeadWidth = 0; //实际的表格列宽度
        protected int fixedColumn = -1; //锁定列
        protected bool _showAdvance = false; //当前显示高级查询状态
        CheckBox chk = null; //是否启用高级查询的复选框
        private bool _searchMk = false; //绑定数据时是否是点击了查询
        private ToolStripButton btnOrder = null;
        private List<Model.TextValuePair> cols = null;
        protected bool isAddAdvanceButton = true; //是否添加高级查询面板和自定义排序按钮
        protected string pageKey = string.Empty; //该属性用来作为键，查询页面布局信息
        protected bool HasSummary = false;

        protected bool IsQueryComponent = false;

        #region 属性

        private bool _isNullData = false;
        protected bool IsNullData
        { get { return _isNullData; } }

        //分页对象
        public UI.Common.Pager MyPager = null;

        public BaseMain()
        {
            InitializeComponent();

            if (!base.isDebug)
            {
                pageKey = this.GetType().FullName;
                _pageInit();
                winpg.PageIndex = 1;
                InitGrid(); //c初始化表格控件
                AddToolButton();
            }
        }

        public BaseMain(string modulecode, string action)
        {
            this.ModuleCode = modulecode;
            this.Action = action;

            InitializeComponent();

            if (!base.isDebug)
            {
                pageKey = this.GetType().FullName;
                _pageInit();
                winpg.PageIndex = 1;
                InitGrid(); //c初始化表格控件
                AddToolButton();
            }
        }

        #endregion

        /// <summary>
        /// 初始化表格控件
        /// </summary>
        protected virtual void InitGrid()
        {
            LoadGridLayout();

            DataTable dtCol = PageCache.GetLayout(pageKey, PageControlType.MainCtl);
            if (dtCol == null) return;

            this.dgvMain.AutoGenerateColumns = false;
            PsDataGridViewTextBoxColumn col = null;
            Model.TextValuePair tv = null; //绑定下拉框
            int width = 0;

            foreach (DataRow dr in dtCol.Rows)
            {
                col = new PsDataGridViewTextBoxColumn();
                col.Name = dr["colname"].ToString();
                col.DataPropertyName = col.Name;
                col.ColType = (PsDataType)Convert.ToInt32(dr["coltype"]);

                string format = Validation.ToString(dr["fmt"]);
                if (string.IsNullOrEmpty(format)
                    && (col.ColType == PsDataType.Date || col.ColType == PsDataType.Date))
                {
                    format = "yyyy-MM-dd";
                }

                col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                col.HeaderText = dr["headcn"].ToString();
                col.IsQuery = ("y" == dr["isquery"].ToString().ToLower());
                col.Visible = ("n" == dr["isshow"].ToString().ToLower()); //数据库中isshow y和n刚好搞反了
                width = Validation.ToInt(dr["columnwidth"]); //字段宽度 
                col.RefCols = Validation.ToString(dr["tp8"]).ToLower();
                col.Width = col.DefaultWidth = col.Visible == false ? 0 : ( //字段宽度
                        (0 == width) ? GridViewUtil.Entity.GetHeadWidth(col.HeaderText) : width
                    );
                gridViewHeadWidth += col.Width;

                //列别名
                col.OtherName = (Validation.IsNull(dr["oname"]) ? col.Name : dr["oname"].ToString());

                col.ReadOnly = true;

                if (Global.IsNumType(col.ColType))
                    col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

                if (!string.IsNullOrEmpty(format))
                {
                    col.DefaultCellStyle.Format = format;
                }

                if (col.IsQuery && col.Visible == true)
                {
                    tv = new Model.TextValuePair(col.HeaderText, col.Name);
                    this.cbxField.Items.Add(tv);

                    tv.DataType = col.ColType;
                    tv.OtherName = col.OtherName;

                    if (null == cols)
                    {
                        cols = new List<Model.TextValuePair>();
                    }

                    cols.Add(tv);
                    //高级查询
                    this.sitemMain.AddColumn(tv);
                }

                this.dgvMain.Columns.Add(col);
            }

            this.sitemMain.CreateSearchPanel();
            if (this.cbxField.Items.Count > 0) this.cbxField.SelectedIndex = 0;
        }

        protected virtual void LoadGridLayout() { }

        //初始化
        private void _pageInit()
        {
            //隔行换色
            this.dgvMain.RowsDefaultCellStyle.BackColor = Color.White;
            this.dgvMain.BackgroundColor = Color.FromArgb(236, 241, 245);
            this.dgvMain.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(246, 250, 255);

            if (isAddAdvanceButton)
            {
                //添加高级查询复选框
                chk = new CheckBox();
                chk.Name = "chk_Advance";
                chk.Text = "高级查询";
                chk.BackColor = Color.Transparent;
                chk.Click += new EventHandler(chk_Click);

                ToolStripControlHost host = new ToolStripControlHost(chk);
                host.BackgroundImage = base.Imgs.Images[3];
                host.ToolTipText = "点击显示或隐藏高级查询栏";
                this.tspTop.Items.Insert(4, host);//用宿主来承载任何控件
            }

            if (!Context.IsSuperUser)
            {
                自定义列宽ToolStripMenuItem.Visible = false;
            }
        }

        //高级查询的复选框点击时
        void chk_Click(object sender, EventArgs e)
        {
            AdvanceQueryClick(sender);
        }

        protected virtual void AdvanceQueryClick(object sender)
        {
            CheckBox chk = sender as CheckBox;
            if (chk == null) return;
            int heightOfUp = IsQueryComponent ? 23 : 52; //高级查询栏离页面顶端的距离，工具栏 + 窗口顶端
            int formSpaceHeight = IsQueryComponent ? -26 : 21; //-21乃是底部多出来的部分 + 顶部没有空隙

            this.scntMain.Width = IsQueryComponent ? this.Width - 5 : this.scntMain.Width;

            if (_showAdvance == false) //当前状态为显示高级查询栏
            {
                chk.BackColor = Color.FromArgb(22, 94, 173);
                chk.ForeColor = Color.White;

                this.sitemMain.Visible = true;
                this.sitemMain.Location = new Point(0, heightOfUp);
                this.sitemMain.Size = new Size(this.scntMain.Width, this.sitemMain.Height);

                this.dgvMain.Anchor = AnchorStyles.None;//AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left;
                this.dgvMain.Location = new Point(0, heightOfUp + this.sitemMain.Height);
                this.dgvMain.Width = this.scntMain.Width;
                this.dgvMain.Height = this.Height - this.tspTop.Height - this.winpg.Height - this.sitemMain.Height - heightOfUp + formSpaceHeight;//21为QQ皮肤上端的高度
            }
            else//当前状态为隐藏高级查询栏
            {
                chk.BackColor = Color.Transparent;
                chk.ForeColor = Color.Black;

                this.sitemMain.Size = new Size(this.scntMain.Width, this.sitemMain.Height);

                this.dgvMain.Anchor = AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top;
                this.dgvMain.Location = new Point(0, heightOfUp);
                this.sitemMain.Visible = false;
                this.dgvMain.Width = this.scntMain.Width;
                this.dgvMain.Height = this.Height - this.tspTop.Height - this.winpg.Height - heightOfUp + formSpaceHeight; //21为QQ皮肤上端的高度
            }

            _showAdvance = !_showAdvance;

        }

        //字段下拉框选项改变了的时候，改变操作符下拉框的选项
        private void cbxField_SelectedIndexChanged(object sender, EventArgs e)
        {
            Model.TextValuePair tv = this.cbxField.SelectedItem as Model.TextValuePair;//当选择的字段名称改变时，重置操作符
            if (tv == null) return;

            string value = txtInput.Text;
            PsDataGridViewTextBoxColumn dc = this.dgvMain.Columns[tv.Value] as PsDataGridViewTextBoxColumn;
            UI.Lib.SearchHelper.GetOperateList(dc.ColType, this.cbxOp); //绑定下拉框
        }

        protected virtual bool OnPageIndexChanging() { return true; }

        protected virtual void BindGrid()
        {
            bool mk = _searchMk; //点击查询按钮的标识
            _searchMk = false;

            //设置数据源的指针位置
            if (BindingManager != null) BindingManager.Position = -1;

            ReturnPageData data;
            if (GetData(out data) == false) return;

            if (null == data || data.AllRowCount == 0)
            {
                _isNullData = true;
                winpg.RowCount = 0;
                this.dgvMain.DataSource = null;
                if (mk)
                    MessageBox.Show("未能查询到相关数据！", "提示");

                HasSummary = false;
                return;
            }

            HasSummary = data.SummaryData != null && data.SummaryData.Rows.Count > 0;
            winpg.RowCount = data.AllRowCount;
            _isNullData = false;

            var dv = data.CurrnetPageData;

            //合计栏
            if (HasSummary)
            {
                foreach (DataRow row in data.SummaryData.Rows)
                {
                    var newRow = dv.NewRow();
                    foreach (DataColumn column in data.SummaryData.Columns)
                    {
                        if (dv.Columns.Contains(column.ColumnName))
                        {
                            newRow[column.ColumnName] = row[column.ColumnName];
                        }
                    }

                    dv.Rows.Add(newRow);
                }
            }

            this.dgvMain.DataSource = dv.DefaultView; //绑定表格

            SetTimeout(100, delegate { ResfreshSummaryStyle(); });

            this.BindingManager = null;//当前的可能是重新加载数据源

            _AddDefaultEvent();

            AfterDataGridBind();//当数据绑定之后执行
        }

        private void ResfreshSummaryStyle()
        {
            //设置最后一个合计行的样式
            if (HasSummary)
            {
                var style = new DataGridViewCellStyle();
                style.Font = new Font("宋体", 10F, FontStyle.Bold);
                style.BackColor = Color.LightGray;

                this.dgvMain.Rows[this.dgvMain.Rows.Count - 1].DefaultCellStyle = style;
            }
        }

        private bool GetData(out ReturnPageData data, bool isSetPageInfo = true)
        {
            if (null == MyPager)
                MyPager = new UI.Common.Pager();

            data = null;

            if (isSetPageInfo)
            {
                MyPager.PageIndex = winpg.PageIndex;
                MyPager.PageSize = winpg.PageSize;
            }

            MyPager.StrWhere = "";

            //得到界面上查询的条件
            bool continues = false;
            MyPager.AutoWhere = GetSearchWhere(ref continues);
            if (continues == false) return false;

            MyPager.IsReadDbSource = true;
            MyPager.PageName = this.pageKey;
            MyPager.Comcode = Context.Comocde; //2011-03-05新加入，为了适应自定义排序的需求
            MyPager.Usercode = Context.LoginName;

            UpdatePager(MyPager); //更新分页的页面信息

            if (isSetPageInfo)
            {
                winpg.PageSize = MyPager.PageSize;
            }

            if (MyPager == null) return true;

            //需要从数据库中读取数据源
            data = MyPager.IsReadDbSource ? CommonHelper.Entity.GetPageList(MyPager) : SetDataSource();

            return true;
        }

        /// <summary>
        /// 更新页面信息
        /// </summary>
        protected virtual void UpdatePager(Common.Pager pager)
        { }

        /// <summary>
        /// 当数据绑定之后执行
        /// </summary>
        protected virtual void AfterDataGridBind() { }

        /// <summary>
        /// 得到Main页面数据源的where
        /// </summary>
        /// <returns></returns>
        protected virtual string GetSearchWhere(ref bool continues)
        {
            continues = true;

            //两种情况，一般普通查询和高级查询
            if (chk == null || chk.Checked == false)
            {
                string value = txtInput.Text;
                if (string.IsNullOrEmpty(value)) return "";

                Model.TextValuePair tv = this.cbxField.SelectedItem as Model.TextValuePair;
                if (tv == null) return "";

                Model.TextValuePair op = this.cbxOp.SelectedItem as Model.TextValuePair;
                if (op == null) return "";

                PsDataGridViewTextBoxColumn dc = this.dgvMain.Columns[tv.Value] as PsDataGridViewTextBoxColumn;

                continues = true;
                return UI.Lib.SearchHelper.GetSearchWhere(tv, dc, value, op, dc.ColType);
            }
            else //高级查询 
            {
                if (!this.sitemMain.CheckGrid(true)) //检查失败
                {
                    continues = false;
                    return "";
                }

                continues = true;
                return this.sitemMain.SearchString;
            }
        }

        //得到数据源
        protected virtual Model.ReturnPageData SetDataSource()
        {
            return null;
        }

        //点击查找
        private void btnSearch_Click(object sender, EventArgs e)
        {
            _searchMk = true;
            BindGrid();
        }

        //页面改变时，触发数据源
        private void winpg_PageIndexChanged(object sender, EventArgs e)
        {
            if (!OnPageIndexChanging()) return;

            BindGrid();
        }

        private void tspView_Click(object sender, EventArgs e)
        {
            DataGridViewRow row = this.GetSelectedRow();
            if (null == row) return;

            if (!IsUntallKey) BaseMain_Deactivate(null, null);//卸载Main页面的键盘事件

            OnViewClick(sender as ToolStripButton, row);

            if (IsUntallKey) BaseMain_Activated(null, null); //增加Main页面的键盘事件
        }

        private void tspAdd_Click(object sender, EventArgs e)
        {
            if (!IsUntallKey) BaseMain_Deactivate(null, null);//卸载Main页面的键盘事件

            OnAddClick(sender as ToolStripButton);

            if (IsUntallKey) BaseMain_Activated(null, null); //增加Main页面的键盘事件
        }

        private void tspEdit_Click(object sender, EventArgs e)
        {
            DataGridViewRow row = this.GetSelectedRow();
            if (null == row) return;

            if (!IsUntallKey) BaseMain_Deactivate(null, null);//卸载Main页面的键盘事件

            OnEditClick(sender as ToolStripButton, row);

            if (IsUntallKey) BaseMain_Activated(null, null); //增加Main页面的键盘事件
        }

        private void tspDel_Click(object sender, EventArgs e)
        {
            DataGridViewRow row = this.GetSelectedRow();
            if (null == row) return;

            if (!IsUntallKey) BaseMain_Deactivate(null, null);//卸载Main页面的键盘事件

            OnDeleteClick(sender as ToolStripButton, row);

            if (IsUntallKey) BaseMain_Activated(null, null); //增加Main页面的键盘事件
        }

        #region 虚拟方法

        protected virtual void OnViewClick(ToolStripButton btn, DataGridViewRow row) { }

        protected virtual void OnAddClick(ToolStripButton btn) { }

        protected virtual void OnEditClick(ToolStripButton btn, DataGridViewRow row) { }

        protected virtual void OnDeleteClick(ToolStripButton btn, DataGridViewRow row) { }
        #endregion

        /// <summary>
        /// 得到选中行 方便公用
        /// </summary>
        /// <returns></returns>
        protected DataGridViewRow GetSelectedRow()
        {
            if (0 == this.dgvMain.Rows.Count || 0 == this.dgvMain.SelectedRows.Count) return null;
            return this.dgvMain.SelectedRows[0];
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!base.isDebug)
            {
                CheckRight(); //检查权限

                BindGrid(); //给Grid绑定数据
                winpg.SetBtnEnabled();

                FixedColumn();
            }

            _AddDefaultEvent();

            _SetFontSize();

            _SetToolBtnStyle();

            //改变Panel
            ChangeComponent();

            isLoadOk = true;
        }

        private void ChangeComponent()
        {
            if (IsQueryComponent == true) //适用于Query中的填充窗口
            {
                this.scntMain.Dock = DockStyle.None;
                this.scntMain.Location = new Point(1, 30);
                this.scntMain.Size = new Size(this.Width - 3, this.Height - 53);
                this.FormBorderStyle = FormBorderStyle.FixedSingle;
                this.MaximizeBox = false;
                this.MinimizeBox = false;

                this.tspTop.Location = new Point(0, 0);
                this.tspTop.Size = new Size(this.Width, this.tspTop.Height);
                this.dgvMain.Anchor = AnchorStyles.None;
                this.dgvMain.Location = new Point(0, 25);
                this.dgvMain.Size = new Size(this.scntMain.Width, this.Height - this.tspTop.Height - this.winpg.Height - 53);//21为QQ皮肤上端的高度
                this.sitemMain.Visible = false;

                this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(126)))), ((int)(((byte)(221)))), ((int)(((byte)(247)))));
            }
        }

        protected void SetNormalMode()
        {
            this.scntMain.Dock = DockStyle.None;
            this.scntMain.Location = new Point(0, 25);
            this.scntMain.Size = new Size(ClientSize.Width, ClientSize.Height - 25);
            this.scntMain.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
            this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(238)))), ((int)(((byte)(247)))));

            this.tspTop.Location = new Point(0, 0);
            this.tspTop.Size = new Size(this.Width, this.tspTop.Height);
            this.dgvMain.Anchor = AnchorStyles.None;
            this.dgvMain.Location = new Point(0, 25);
            this.dgvMain.Size = new Size(this.scntMain.Width, this.Height - this.tspTop.Height - this.winpg.Height - 53);//21为QQ皮肤上端的高度
        }

        public void SetTimeout(double interval, EventHandler action)
        {
            var timer = new System.Timers.Timer(interval);
            timer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e)
            {
                timer.Enabled = false;
                action(sender, new EventArgs());
            };
            timer.Enabled = true;
        }

        #region 权限相关

        private void CheckRight()
        {
            string[] ps = Validation.ToString(CommonHelper.Entity.GetActionList(this.ModuleCode)).Split(',');
            if (ps.Length == 0) //没有权限访问
            {
                MessageBox.Show("您没有操作该模块的任何权限，请联系管理员！", "提示");
                this.InitOk = false;
                this.Close();
                return;
            }

            foreach (ToolStripItem item in tspTop.Items)
            {
                if (item is ToolStripButton)
                {
                    if (item.Tag == null) item.Visible = false; //没有设置Tag的按钮隐藏
                    if (item.Tag.ToString() != "S" && Array.IndexOf(ps, item.Tag.ToString()) == -1)
                        item.Visible = false;
                }
            }
        }

        #endregion

        #region 热键相关

        protected void BaseMain_Activated(object sender, EventArgs e)
        {
            IsUntallKey = false;
        }

        protected void BaseMain_Deactivate(object sender, EventArgs e)
        {
            IsUntallKey = true;
        }
        #endregion

        private void BaseMain_Leave(object sender, EventArgs e)
        {

        }

        private void BaseMain_FormClosing(object sender, FormClosingEventArgs e)
        {
        }

        protected void BaseMain_ClientSizeChanged(object sender, EventArgs e)
        {
            AutoSize();

            //如果单元格的宽度之和小于我的GridView的宽度，则自动填充满
            //this.dgvMain.AutoSizeColumnsMode = (gridViewHeadWidth < this.dgvMain.ClientSize.Width)
            //                                       ? DataGridViewAutoSizeColumnsMode.Fill
            //                                       : DataGridViewAutoSizeColumnsMode.None;
        }

        protected void BaseMain_Shown(object sender, EventArgs e)
        {
            BaseMain_ClientSizeChanged(sender, e);
        }

        protected virtual void AutoSize()
        {

        }

        protected virtual void AddToolButton() { }

        protected void FixedColumn()
        {
            if (fixedColumn < 0 || fixedColumn > this.dgvMain.ColumnCount) return;
            this.dgvMain.Columns[fixedColumn].Frozen = true;
        }

        /// <summary>
        /// 行改变之后触发
        /// </summary>
        /// <param name="rowIndex"></param>
        protected virtual void AfterRowChanged(int rowIndex) { }

        //添加默认事件
        private void _AddDefaultEvent()
        {
            object datasource = this.dgvMain.DataSource;
            if (null == datasource) return;
            BindingManager = this.BindingContext[datasource];
            BindingManager.PositionChanged -= new EventHandler(BindingManager_PositionChanged);
            BindingManager.PositionChanged += new EventHandler(BindingManager_PositionChanged);

            if (0 != this.dgvMain.Rows.Count) AfterRowChanged(0);
        }

        void BindingManager_PositionChanged(object sender, EventArgs e)
        {
            int tRowIndex = BindingManager.Position;

            AfterRowChanged(tRowIndex);
        }

        //设置字体大小
        void _SetFontSize()
        {
            sitemMain.Font = this.cntLeft.Font = Global.AllFont;
            this.tspTop.Font = dgvMain.Font = Global.ToolBarFont;


            this.dgvMain.ColumnHeadersDefaultCellStyle.Font = Global.AllFont;
            this.dgvMain.RowsDefaultCellStyle.Font = Global.AllFont;
        }

        private void BaseMain_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Insert:    //按下的是Insert
                    if (CanClickButton(this.tspAdd)) tspAdd_Click(this.tspAdd, null);
                    break;
                case Keys.F2:    //按下的是F2，修改
                    if (CanClickButton(this.tspEdit)) tspEdit_Click(this.tspEdit, null);
                    break;
                case Keys.Delete:    //按下的是Del
                    if (CanClickButton(this.tspDel)) tspDel_Click(this.tspDel, null);
                    break;
                case Keys.End:    //按下的是End == 进入查询 让文本框得到焦点
                    if (this.txtInput.Visible == true) txtInput.Focus();
                    break;
                case Keys.Home:    //按下的是Home，Id号为104 == 执行查询
                    if (CanClickButton(this.btnSearch)) btnSearch_Click(btnSearch, null);
                    break;
                case Keys.PageDown:    //按下的是page down，Id号为105 == 查看明细
                    if (CanClickButton(this.tspView)) tspView_Click(tspView, null);
                    break;
                case Keys.PageUp:    //按下的是page up，Id号为106 == 返回及关闭
                    this.Close();
                    break;
                case Keys.F4:    //按下的是F4，Id号为107 == 返回及关闭
                    this.Close();
                    break;
                case Keys.F5:    //按下的是F5，Id号为108 == 调用子菜单
                    break;
                case Keys.F9: //排序
                    自定义排序ToolStripMenuItem_Click(null, null);
                    break;
            }

            if (e.Alt && e.KeyCode == Keys.Up) //首页
            {
                this.winpg.BtnFirstClick();
            }
            else if (e.Alt && e.KeyCode == Keys.Down) //尾页
            {
                this.winpg.BtnEndClick();
            }
            else if (e.Alt && e.KeyCode == Keys.Left) //<-
            {
                this.winpg.BtnPreClick();
            }
            else if (e.Alt && e.KeyCode == Keys.Right) //->
            {
                this.winpg.BtnNextClick();
            }

            FormKeyDown(e);
        }

        protected virtual void FormKeyDown(KeyEventArgs e) { }

        private void dgvMain_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) //双击Left ，打开明细窗口
            {
                if (CanClickButton(this.tspEdit)) //有修改，双击则修改，无则显示明细
                {
                    this.tspEdit.PerformClick();
                }
                else if (CanClickButton(this.tspView))
                {
                    this.tspView.PerformClick();
                }
            }
        }

        void _SetToolBtnStyle()
        {
            ToolStripButton btn = null;
            foreach (ToolStripItem item in this.tspTop.Items)
            {
                if (item is ToolStripButton)
                {
                    btn = item as ToolStripButton;
                    btn.BackgroundImage = base.Imgs.Images[3];
                }
            }
        }

        private void cntLeft_Opening(object sender, CancelEventArgs e)
        {
            e.Cancel = !_isClickGridViewTitle;
        }

        private bool _isClickGridViewTitle = false;

        private void dgvMain_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
        }

        private void dgvMain_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            _isClickGridViewTitle = (e.Button == MouseButtons.Right && e.RowIndex == -1);
        }

        private void 导出全部数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReturnPageData data;

            if (MyPager == null)
                MyPager = new Pager();

            MyPager.PageIndex = 1;
            MyPager.PageSize = 2000; //最大支持2000条记录

            if (GetData(out data, false) == false)
                return;

            if (null == data.CurrnetPageData)
            {
                MessageBox.Show("没有可以导出的数据", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            ExportExcel.DataTableToExcel(data.CurrnetPageData, this.dgvMain);
        }

        private void 导出本页数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportExcel.DataGridViewToExcel(this.dgvMain);
        }

        void ResetColumnWidth()
        {
            foreach (PsDataGridViewTextBoxColumn dc in this.dgvMain.Columns)
            {
                if (dc.Visible == false) continue;
                dc.Width = dc.DefaultWidth;
            }
        }

        private void 自定义排序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var frmOrder = new UI.CommonForm.FrmCustomOrder(this.Text, this.pageKey, this.cols);
            if (frmOrder.ShowDialog() == DialogResult.OK)
            {
                winpg.PageIndex = 1;
                BindGrid(); //重新加载数据
            }
        }

        private void 自定义列宽ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var frmOrder = new UI.CommonForm.FrmResizeWidth(this.Text, this.pageKey, "Main");
            frmOrder.ShowDialog();

            if (frmOrder.IsReloadWIn)
            {
                Hashtable table = frmOrder.colsWidth;
                gridViewHeadWidth = 0;
                int width = 0;
                PsDataGridViewTextBoxColumn tc = null;
                foreach (DataGridViewColumn dc in this.dgvMain.Columns)
                {
                    if (dc is PsDataGridViewTextBoxColumn)
                    {
                        tc = dc as PsDataGridViewTextBoxColumn;
                        if (table.Contains(dc.Name))
                        {
                            width = Convert.ToInt32(table[dc.Name]);

                            //字段宽度
                            tc.Width = tc.DefaultWidth = tc.Visible == false
                                ? 0
                                : ((0 == width) ? GridViewUtil.Entity.GetHeadWidth(tc.HeaderText) : width);

                            gridViewHeadWidth += tc.Width;
                        }
                    }
                }
            }
        }

        private void dgvMain_KeyDown(object sender, KeyEventArgs e)
        {
            OnGridKeyDown(e);
        }

        protected virtual void OnGridKeyDown(KeyEventArgs e)
        { }
    }
}
